from django.db import models


class MyCharField(models.Field):
    """
    自定义的char类型的字段类
    """

    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super(MyCharField, self).__init__(max_length=max_length, *args, **kwargs)

    def db_type(self, connection):
        """
        限定生成数据库表的字段类型为char,长度为max_length指定的值
        """

        return 'char(%s)' % self.max_length


# Create your models here.
class Person(models.Model):
    pid = models.AutoField(primary_key=True)  # 自己创建主键
    name = models.CharField(max_length=32)  # varchar(32)
    age = models.IntegerField()  # 存储的数据类型为整型，范围+-21亿
    birth = models.DateTimeField(auto_now=True)  # 新增数据时自动保存当前时间

    def __str__(self):
        return "{}--{}".format(self.name, self.age)


class Publisher(models.Model):
    name = models.CharField(max_length=32, verbose_name='出版社名称')  # 属性名称


class Book(models.Model):
    name = models.CharField(max_length=32, verbose_name='书名')
    pub = models.ForeignKey('Publisher', on_delete=models.CASCADE,
                            related_name='books')  # 创建外键，关联删除,2.反向查询可直接books,不用book_set命令
    price = models.DecimalField(max_digits=5, decimal_places=2)  # 999.99(总位数为5，小数为2)
    sale = models.IntegerField()
    kucun = models.IntegerField()


class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name='姓名')
    books = models.ManyToManyField('Book', related_name='authors')
